package com.tywj.panda.driver.more

import android.content.Intent
import android.os.Bundle
import androidx.collection.ArrayMap
import androidx.lifecycle.Observer
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.tywj.lib.core.common.extension.onClick
import com.tywj.lib.core.common.util.BarUtil
import com.tywj.lib.core.common.util.LogUtil
import com.tywj.lib.core.common.util.ResourcesUtil
import com.tywj.lib.net.retrofit.request.BaseRequest
import com.tywj.lib.route.RouteParam
import com.tywj.panda.customer.common.tool.PermissionTool
import com.tywj.panda.customer.common.view.dialog.showByCZConfig
import com.tywj.panda.customer.common.view.paging.BasePagingActivitySearch
import com.tywj.panda.driver.R
import com.tywj.panda.driver.api.DriverApi
import com.tywj.panda.driver.api.SelectedDateDialog
import com.tywj.panda.driver.entity.DriverTaskEntity
import com.tywj.panda.driver.event.DriverEvent
import com.tywj.panda.driver.route.DriverRoute
import com.tywj.panda.driver.service.GPSLocationService
import com.tywj.panda.driver.task.DriverTaskAdapter
import com.tywj.panda.driver.tool.ServiceTool
import kotlinx.android.synthetic.main.driver_activity_more_task.*

/**
 * 更多班次
 */
@Route(path = DriverRoute.DRIVER_MORE_TASK)
class DriverMoreTaskActivity :
    BasePagingActivitySearch<DriverTaskEntity, DriverTaskEntity.DataBean>(DriverTaskEntity.DataBean::class.java) {

    companion object {
        const val PARAMS_DATE = "date"
    }

    //全部任务
    private var taskType = "2"

    //当前时间
    private var currentTime = ""

    //开始打卡或结束打卡状态
    private var workStatus = 1;

    /**
     * 选择日期
     */
    private val selectedDialog by lazy { initSelectedBuyDialog() }

    override fun getLayoutID(): Int = R.layout.driver_activity_more_task

    override fun initVariable(savedInstanceState: Bundle?) {
        super.initVariable(savedInstanceState)
        currentTime = RouteParam(this).getString(PARAMS_DATE)
    }


    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        with(mStatusLayout) {
            setEmptyLayoutIcon(R.drawable.common_data_is_empty)
            setEmptyLayoutTitle(R.string.driver_today_all_task)
        }
        BarUtil.setStatusBarColor(this, ResourcesUtil.getColor(R.color.common_white))
        BarUtil.setStatusBarLightMode(this.window, true)

        titleLayout.getTitleTextView().text = currentTime
    }

    override fun initListener() {
        super.initListener()

        titleLayout.getRightTextView().onClick {
            selectedDialog.showDialog(getFragmentManagerInstance())
        }

        selectedDialog.setSelectedDateTime {
            currentTime = it
            mPagingHelper.refresh()
            titleLayout.getTitleTextView().text = currentTime
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val bean = mAdapter.data[position]
            // 跳转至班次详情页
            DriverRoute.toBusDetails(bean).navigation(this)
        }


        mAdapter.setOnItemChildClickListener { _, view, position ->
            val bean = mAdapter.data[position]

            when (view.id) {
                //打卡状态
                R.id.tvClockStatus -> {
                    showPunchDialog(bean)
                }
            }
        }

        DriverEvent.refreshTaskEvent.observe(this, Observer {
//            shortToast("refreshTaskEvent 开始刷新界面")
//            //优化成局部刷新
            mPagingHelper.refresh()

            if (workStatus == 2) {
                val intent = Intent(this, GPSLocationService::class.java)
                intent.putExtra(GPSLocationService.PARAMS_BEAN, "")
                intent.putExtra(GPSLocationService.PARAMS_WORK_StATUS, workStatus)
                stopService(intent)
            }
        })
    }

    override fun getRecyclerViewAdapter(): BaseQuickAdapter<DriverTaskEntity.DataBean, *> {
        return DriverTaskAdapter()
    }

    override fun getRequest(): BaseRequest<*> = DriverApi.getTaskList()

    override fun getRequestParams(): ArrayMap<String, String> {
        return DriverApi.listTaskParams(taskStatus = taskType, selectedTime = currentTime)
    }


    override fun getRequestParamsLoadMore(): ArrayMap<String, String> {
        return DriverApi.listTaskParams(
            taskStatus = taskType,
            selectedTime = currentTime,
            time = mAdapter.data.last().createTime
        )
    }


    private fun initSelectedBuyDialog(): SelectedDateDialog {
        //as？如果不兼容 会返回为null  ?:为空时会初始化
        return getFragmentManagerInstance().findFragmentByTag(SelectedDateDialog.TAG) as? SelectedDateDialog
            ?: SelectedDateDialog()
    }

    private fun showPunchDialog(bean: DriverTaskEntity.DataBean) {
        MaterialDialog(this)
            .title(R.string.common_prompt_title)

            .message(
                if (isStartAction(bean)) {
                    R.string.driver_start_clock_tips
                } else {
                    R.string.driver_end_clock_tips
                }
            )

            .negativeButton(R.string.common_negative)
            .positiveButton(R.string.common_positive) {
                //打卡
                PermissionTool.location {
                    workStatus = if (isStartAction(bean)) {
                        //开始打卡
                        1
                    } else {
                        //结束打卡
                        2
                    }
                    val intent = Intent(this, GPSLocationService::class.java)
                    intent.putExtra(GPSLocationService.PARAMS_BEAN, bean)
                    intent.putExtra(GPSLocationService.PARAMS_WORK_StATUS, workStatus)
                    startService(intent)
                }

            }
            .showByCZConfig()
    }

    //是否是开始打卡
    private fun isStartAction(bean: DriverTaskEntity.DataBean): Boolean {
        return bean.startPunch == 0 && bean.endPunch == 0
    }

}